package com.kkb.cubemall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kkb.cubemall.common.utils.PageUtils;
import com.kkb.cubemall.common.utils.Query;
import com.kkb.cubemall.product.dao.CategoryDao;
import com.kkb.cubemall.product.entity.CategoryEntity;
import com.kkb.cubemall.product.service.CategoryService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        List<CategoryEntity> entities = baseMapper.selectList(null);

        List<CategoryEntity> levelOneMenus = entities.stream().filter(
                categoryEntity -> categoryEntity.getParentId().equals(0)
        ).map((menu) -> {
            menu.setChildren(getChildren(menu, entities));
            return menu;
        }).collect(Collectors.toList());

        return levelOneMenus;
    }

    @Override
    public void removeMenusByIds(List<Integer> asList) {
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Integer[] findCategoryPathById(Integer categoryId) {
        List<Integer> list = new ArrayList<>();
        getPath(categoryId, list);
        Collections.reverse(list);
        return list.toArray(new Integer[list.size()]);
    }

    private void getPath(Integer categoryId, List<Integer> list) {
        list.add(categoryId);
        CategoryEntity entity = this.getById(categoryId);
        if (entity.getParentId() != 0) {
            getPath(entity.getParentId(), list);
        }
    }

    private List<CategoryEntity> getChildren(CategoryEntity currentEntity, List<CategoryEntity> entities) {
        List<CategoryEntity> list = entities.stream().filter(
                categoryEntity -> categoryEntity.getParentId().equals(currentEntity.getId())
        ).map((menu) -> {
            menu.setChildren(getChildren(menu, entities));
            return menu;
        }).collect(Collectors.toList());
        return list;
    }

}